import java.util.*;

public class Leetcode {

    static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
    }
    //非递归前序遍历
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> ret = new LinkedList();
        if(root == null){
            return ret;
        }
        TreeNode cur = root;
        //用栈来实现
        Deque<TreeNode> stack = new ArrayDeque();
        while(cur != null||!stack.isEmpty()){
            while(cur != null){
                stack.push(cur);
                ret.add(cur.val);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            cur = top.right;
        }
        return ret;
    }
    //非递归中序遍历
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ret = new LinkedList();
        if(root == null){
            return ret;
        }
        TreeNode cur = root;
        Deque<TreeNode> stack = new LinkedList();
        while(cur != null || !stack.isEmpty()){
            while(cur != null){
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.pop();
            ret.add(top.val);
            cur = top.right;
        }
        return ret;
    }
    //非递归后序遍历
    //非递归实现后序遍历
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null){
            return list;
        }
        TreeNode cur = root;
        TreeNode prev = null;
        Deque<TreeNode> stack = new ArrayDeque<>();
        while (cur != null || !stack.isEmpty()){
            while (cur!=null){
                stack.push(cur);
                cur = cur.left;
            }
            TreeNode top = stack.peek();
            if(top.right == null || top.right == prev){
                list.add(top.val);
                stack.pop();
                prev = top;
            }else{
                cur = top.right;
            }
        }
        return list;
    }
}
